package com.framework.validated.controller;

import com.framework.validated.common.R;
import com.framework.validated.exception.ExceptionEnum;
import com.framework.validated.pojo.User;
import jakarta.validation.constraints.Size;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    /**
     * 验证全局异常是否存在错误
     *
     * @return
     */
    @GetMapping("demo")
    public R demo() {
        int i = 1 / 0;
        return R.success();
    }

    /**
     * 验证返回统一格式
     *
     * @return
     */
    @GetMapping("info")
    public R info() {
        return R.success();
    }

    /**
     * json请求
     *
     * @param user JSON
     * @return
     */
    @PostMapping("data")
    public R data(@RequestBody User user) {
        return R.success(user.toString());
    }

    /**
     * 启动校验：验证接收情况
     *
     * @param user
     * @return
     */
    @PostMapping("check")
    public R check(@Validated @RequestBody User user) {
        /*
        报错信息，通过Exception 全局异常捕获，无用的信息太多，我们想精准获取需要使用BindingResult
        {"code": 500,
        "msg": "error",
        "data": "class org.springframework.web.bind.MethodArgumentNotValidException:
        Validation failed for argument [0] in public com.framework.validated.common.R com.framework.validated.controller.UserController.check(com.framework.validated.pojo.User) with 2 errors: [Field error in object 'user' on field 'active': rejected value [false]; codes [AssertTrue.user.active,AssertTrue.active,AssertTrue.java.lang.Boolean,AssertTrue]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.active,active]; arguments [];
         default message [active]]; default message [必须同意使用协议！]]
         [Field error in object 'user' on field 'age': rejected value [0];
          codes [Min.user.age,Min.age,Min.java.lang.Integer,Min];
           arguments [org.springframework.context.support.DefaultMessageSourceResolvable:
            codes [user.age,age]; arguments []; default message [age],1]; default message [年龄最小值不能小于1]] "
        }
        * */
        return R.success(user.toString());
    }

    /**
     * &#064;Validated注解必须在参数列表的最前面，BindingResult  必须在User之后，否则不生效
     * @param user
     * @param result
     * @return
     */
    @PostMapping("check-b")
    public R checkB(@Validated @RequestBody User user, BindingResult result) {

        // 如果校验失败，则进入
        if (result.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            result.getFieldErrors().forEach((e) -> {
                map.put(e.getField(), e.getDefaultMessage());
            });
            return R.error(ExceptionEnum.DATA_VALIDATED_ERROR,map);
        }
        return R.success(user.toString());
    }

    /**
     * 数据校验注解，不校验实体类，则不需要使用@Validated注解，直接放到方法参数中使用
     * @param name
     * @return
     */
    @GetMapping("check-c")
    public R checkC(@RequestParam("name") @Size(min = 2) String name) {
        return R.success(name);
    }


}
